<?php

namespace App\Http\Controllers\Api;

use App\Ad\Docking\DockingBase;
use App\Commons\CommonConstant;
use App\Http\Controllers\Controller;
use App\Models\AdMonitor;
use App\Models\FirstupAd;
use App\Models\Log\LogAdPostbackVirtual;
use App\Models\Orders;
use Illuminate\Http\Request;

class AdPostbackVirtualController extends Controller
{
    public function report(Request $request)
    {
        $id = $request->input('id') ?? 0;
        $log = LogAdPostbackVirtual::find($id);
        if (!$log) {
            return yqerr(6029);
        }

        $firstup_ad = FirstupAd::find($log->firstup_ad_id);
        $monitor    = AdMonitor::find($firstup_ad->monitor_id);
        if (!$monitor) {
            $monitor = new AdMonitor;
        }

        $mod              = new Orders;
        $mod->id          = $log->id;
        $mod->call_money  = $log->amount;
        $mod->create_time = $log->create_time;

        $docking = DockingBase::getClass($log->media_docking_id);
        try {
            $status = $docking->postbackToMedia(CommonConstant::EVENT_PAY, $monitor, $firstup_ad, $mod);
        } catch (\Throwable $th) {
            $status = LogAdPostbackVirtual::STATUS_ERROR;
        }

        $log->status      = $status;
        $log->report_time = time();
        $log->save();

        if ($status == LogAdPostbackVirtual::STATUS_SUCC) {
            return yqok();
        }

        return yqerr($status);
    }
}
